import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(menus: any, route: any) {
    if (route.meta && route.meta.permissionCode) {
        return menus.indexOf(route.meta.permissionCode) != -1
    } else {
        return true
    }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes: Array<any>, menus: any) {
    return routes
        .filter((route) => {
            return hasPermission(menus, route)
        })
        .map((item) => {
            item = Object.assign({}, item)
            if (item.children) {
                item.children = filterAsyncRoutes(item.children, menus)
            }
            return item
        })
}

const state = {
    routers: constantRoutes,
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state: any, routes: any) => {
        state.addRoutes = routes
        state.routers = constantRoutes.concat(routes)
    }
}

const actions = {
    generateRoutes({ commit }: any, { menus }: any) {
        return new Promise((resolve) => {
            let accessedRoutes
            accessedRoutes = filterAsyncRoutes(asyncRoutes, menus)
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
